<template>
  <div class="store-info">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <card class="add-info-card" title="基本信息">
        <page-form-row>
          <page-form-item field="parentOrgId" label="上级机构" required>
            <!-- 编辑的时候显示名字，防止机构拉黑 -->
            <i-input v-if="status == 'edit'" v-model="form.parentOrgName" disabled />
            <a-tree-select
              v-else
              v-model="form.parentOrgId"
              :allow-search="true"
              :allow-clear="true"
              :data="treeData"
              placeholder="请选择"
              :filter-tree-node="filterTreeNodeFn"
            />
          </page-form-item>
          <page-form-item field="siteName" label="门店名称" required>
            <i-input placeholder="请输入" v-model="form.siteName" :max-length="50" />
          </page-form-item>
          <page-form-item field="lnglat" label="门店坐标" required>
            <i-input placeholder="请选择" v-model="form.lnglat" readonly @click="siteCoordinatesClickFn" />
          </page-form-item>
          <page-form-item field="cityCode" label="城市" required>
            <remote-select v-model="form.cityCode" type="area_city" @change="changeCityFn" />
          </page-form-item>
          <page-form-item field="districtCode" label="区域">
            <remote-select
              v-model="form.districtCode"
              :params="{
                parentCode: form.cityCode,
              }"
              :mustParentShow="!form.cityCode"
              mustParentTip="请先选择城市"
              type="area_area"
            />
          </page-form-item>
          <page-form-item field="address" label="地址" required>
            <i-input placeholder="请输入" v-model="form.address" />
          </page-form-item>
          <page-form-item class="mb-0" field="siteCarPark" label="门店车场">
            <a-input-search
              placeholder="请输入"
              v-model="form.siteCarPark"
              button-text="同机构地址"
              search-button
              @search="sameInstitutionFn"
            />
          </page-form-item>
          <page-form-item class="mb-0 store-time" label="门店营业时间" required>
            <page-form-item class="mb-0 store-time-item" field="fromTime" size="1/2">
              <a-time-picker
                style="width: 100%"
                v-model="form.fromTime"
                disableConfirm
                placeholder="开始时间"
                format="HH:mm"
                :step="{
                  minute: 30,
                }"
              />
            </page-form-item>
            <page-form-item class="mb-0 store-time-item" field="toTime" size="1/2">
              <a-time-picker
                style="width: 100%"
                v-model="form.toTime"
                disableConfirm
                placeholder="结束时间"
                format="HH:mm"
                :step="{
                  minute: 30,
                }"
              />
            </page-form-item>
          </page-form-item>
          <page-form-item class="mb-0" field="status" label="门店状态" required>
            <a-select placeholder="请选择" v-model="form.status" allow-clear>
              <a-option v-for="item in dict.siteStatus" :key="item.value" :label="item.label" :value="item.value" />
            </a-select>
          </page-form-item>
        </page-form-row>
      </card>
      <card class="add-info-card link-info" title="联系信息">
        <div class="link-man-list">
          <div class="link-man-item" v-for="(item, index) in form.contactList" :key="index">
            <page-form-row>
              <page-form-item :field="`contactList.${index}.name`" :label="index == 0 ? '联系人' : ''">
                <a-input placeholder="请输入" v-model="item.name" :max-length="20" />
              </page-form-item>
              <page-form-item :field="`contactList.${index}.phone`" :label="index == 0 ? '联系电话' : ''" style="position: relative">
                <a-input placeholder="请输入" v-model.trim="item.phone" :maxlength="20" />
                <operate-list
                  :style="{ top: index > 0 ? '0px' : '26px' }"
                  :index="index"
                  :length="form.contactList.length"
                  @add="newLinkManFn"
                  @delete="delLinkManFn(index)"
                />
              </page-form-item>
            </page-form-row>
          </div>
        </div>
      </card>

      <card
        class="add-info-card link-info carHousekeep-card"
        labelTooltipContent="工单开启车管家模式后，所有的长/短租订单由车管家针对交车人、换车人、还车人派单，相关负责人接单后，进行操作"
        :showDivider="false"
      >
        <template #title>
          <div>
            配置车管家
            <span v-show="carHousekeep.isOpenCarHousekeep == 1" class="carHousekeep-star">*</span>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center">
            <span v-show="carHousekeep.isOpenCarHousekeep == 1" class="carHousekeep-extra">（至少需要配置一位车管家）</span>
            <a-button class="add-carHousekeep" type="primary" @click="addCarHousekeep" v-if="form?.carHousekeepList.length < 20">
              <icon-plus size="14" class="mr-2" /> 添加车管家
            </a-button>
          </div>
        </template>
        <!-- StaffSelect 初始化加载在 form 数据前，会报错 -->
        <page-form-row>
          <page-form-item :label="`车管家-${index + 1}`" v-for="(_, index) in form?.carHousekeepList" :key="index">
            <StaffSelect
              :carHousekeepList="form?.carHousekeepList"
              :isOpenCarHousekeep="carHousekeep.isOpenCarHousekeep"
              :index="index"
              :storeInfo="{ siteId: form.id }"
              :popupContainer="'.page-container'"
            />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
    <!-- 坐标选择 -->
    <lnglat-picker-modal ref="lnglatPickerModalRef" @change="pointChangeFn" />
  </div>
</template>

<script setup name="MerchantStoreInfo">
  import StaffSelect from '@/views/business/workOrder/car-steward/components/staff-select.vue'

  import { ref, inject, onMounted, onActivated } from 'vue'
  import { getSelectAuthList } from '@/api/asset/site'
  import { isMobile } from '@/utils/validate.js'
  import operateList from './operte-list.vue'
  import { Message } from '@arco-design/web-vue'
  import { getCarHousekeepDetail } from '@/api/business/workorder'

  const props = defineProps({
    status: {
      type: String,
      default: 'add',
    },
  })

  const validatorFn = (value, cb) => {
    if (!value || value == '') {
      cb()
    } else {
      if (!isMobile(value)) {
        cb('手机号格式不正确')
      }
    }
  }
  const contactPhoneRule = [{ required: false, validator: validatorFn, trigger: 'change' }]
  // 接收父组件
  const form = inject('form')
  const dict = inject('dict')
  console.log(form, 'form')

  // 车管家模式
  const carHousekeep = ref({
    isOpenCarHousekeep: 0,
  })

  // 添加车管家
  const addCarHousekeep = () => {
    form.value.carHousekeepList.push({ staffId: undefined })
  }

  // 获取车管家详情
  const getStaffDetail = () => {
    getCarHousekeepDetail().then((res) => {
      carHousekeep.value = res.result
    })
  }

  const filterTreeNodeFn = (searchValue, nodeData) => {
    return nodeData.title.toLowerCase().indexOf(searchValue.toLowerCase()) > -1
  }
  const lnglatPickerModalRef = ref(null)
  const siteCoordinatesClickFn = () => {
    lnglatPickerModalRef.value.open(form.value.lnglat)
  }
  // 坐标选择
  const pointChangeFn = (lnglat, option) => {
    form.value.lnglat = lnglat.toString()
    form.value.longitudeGd = lnglat[0]
    form.value.latitudeGd = lnglat[1]
    if (option) {
      const adcode = option.addressComponent.adcode
      form.value.address = option.formattedAddress
      form.value.cityCode = String(parseInt(adcode / 100) * 100)
      form.value.districtCode = adcode
      // fixme: 坐标选择无法返回省份 code，此时无法更新 form.provinceCode
      // 如果直接调接口目前也没问题 provinceCode 非必填，且后端会补 provinceCode 数据

      formRef.value.validateField(['lnglat', 'cityCode', 'address'])
    }
  }
  // 城市发生改变 补充省份 code
  const changeCityFn = (value, option) => {
    form.value.provinceCode = option?.parentCode || undefined
    form.value.districtCode = undefined
  }
  // 同机构地址
  const sameInstitutionFn = () => {
    if (form.value.address) {
      form.value.siteCarPark = form.value.address
    }
  }
  // 表结构转化为树结构
  const setTreeData = (arr) => {
    // 删除所有的children,以防止多次调用
    arr.forEach(function (item) {
      delete item.children
    })
    let map = {} //构建map
    arr.forEach((i) => {
      map[i.id] = i //构建以id为键 当前数据为值
    })
    let treeData = []
    arr.forEach((child) => {
      const mapItem = map[child.parentId] //判断当前数据的parentId是否存在map中
      if (mapItem) {
        //存在则表示当前数据不是最顶层的数据
        //注意： 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变，踩坑点
        ;(mapItem.children || (mapItem.children = [])).push(child) //这里判断mapItem中是否存在child
      } else {
        //不存在则是顶层数据
        child.top = true
        treeData.push(child)
      }
    })
    return treeData
  }
  const rules = ref({
    parentOrgId: { required: true, message: '请选择上级机构', trigger: 'change' },
    siteName: { required: true, message: '请输入门店名称', trigger: 'blur' },
    status: { required: true, message: '请选择门店状态', trigger: 'change' },
    lnglat: { required: true, message: '请选择门店坐标', trigger: 'change' },
    cityCode: { required: true, message: '请选择城市', trigger: 'change' },
    fromTime: { required: true, message: '请选择开始时间', trigger: 'change' },
    toTime: { required: true, message: '请选择结束时间', trigger: 'change' },
    address: { required: true, message: '请输入地址', trigger: 'change' },
  })
  const treeData = ref([])
  getSelectAuthList().then((res) => {
    if (res.code == 200) {
      const result = res.result.map((e) => {
        e.key = e.id
        e.title = e.orgName
        e.value = e.id
        e.label = e.orgName
        e.children = [] //创建子级
        return e
      })
      treeData.value = setTreeData(result)
    }
  })
  const newLinkManFn = () => {
    form.value.contactList.push({ name: '', phone: '' })
  }
  const delLinkManFn = (index) => {
    form.value.contactList.splice(index, 1)
  }

  // 校验
  const validate = () => {
    // 校验
    form.value.errSiteIdList = []
    let useable_count = 0
    form.value.carHousekeepList.forEach((item) => {
      if (item.staffId) {
        useable_count++
      }
      if (item.staffStatusName) {
        useable_count--
        if (item.staffStatusName == '选择重复，请重新选择') {
          useable_count = -99
        }
      }
    })
    if (useable_count <= 0) {
      // 判断是否是新增
      if (form.value.id) {
        form.value.errSiteIdList.push(form.value.id)
      } else {
        // 拦截不配置车管家
        form.value.errSiteIdList.push(1)
      }
    }
  }

  const formRef = ref()
  const validateFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error, scrollErrorFn) => {
        if (error) {
          reject({
            errorKey: 'store-info',
            scrollErrorFn,
          })
        } else {
          validate()
          // 开启再校验
          if (carHousekeep.value.isOpenCarHousekeep && form.value.errSiteIdList.length > 0) {
            Message.warning('请检查配置车管家')
            return false
          }
          const carHousekeepList = form.value.carHousekeepList?.map((item) => item.staffId)
          form.value.siteCarHouseKeepList = carHousekeepList
          resolve()
        }
      })
    })
  }

  onActivated(() => {
    getStaffDetail()
  })

  //这里需要暴露出去不然父组件调用不到这个方法
  defineExpose({
    validateFn,
  })
</script>

<style lang="less" scoped>
  .store-time {
    :deep(.arco-form-item-wrapper-col) {
      width: 100%;
      .store-time-item[field] {
        width: calc(50% - 10px);
      }
      .store-time-item[field] + .store-time-item[field] {
        margin-left: 20px;
      }
    }
    :deep(.arco-form-item-content-flex) {
      align-items: flex-start;
    }
    .store-time-item {
      :deep(.arco-form-item-content-flex) {
        align-items: center;
      }
    }
  }
  .store-info {
    :deep {
      .custom-divider {
        margin: 20px 0 13px 0;
      }
      .arco-card-header {
        padding: 0 0 20px 0 !important;
      }
    }
  }
  .add-carHousekeep {
    font-size: 14px;
    height: 32px;
    line-height: 32px;
    padding: 0 12px;
    color: #fff;
    icon {
      margin-right: 8px;
    }
  }
  :deep(.carHousekeep-card .arco-card-header-extra) {
    flex: 0 0 80%;
  }
  .carHousekeep-star {
    color: #f53f3f;
    vertical-align: sub;
  }
  .carHousekeep-extra {
    color: #f76964;
    font-size: 12px;
  }
</style>
